package com.ljh.onlinetest.configuration.spring.exception;

import com.ljh.onlinetest.base.RestResponse;
import com.ljh.onlinetest.base.SystemCode;
import com.ljh.onlinetest.utils.ErrorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author ljh
 * @ClassName ExceptionHandle.java
 * @createTime 2021年12月20日
 */
@ControllerAdvice
public class ExceptionHandle {
    private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RestResponse handler(Exception e){
        LOGGER.error(e.getMessage(),e);
        return new RestResponse<>(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public RestResponse handler(MethodArgumentNotValidException e){
        String errorMsg = e.getBindingResult().getAllErrors().stream().map(file -> {
            FieldError fieldError = (FieldError) file;
            return ErrorUtil.parameterErrorFormat(fieldError.getField(), fieldError.getDefaultMessage());
        }).collect(Collectors.joining());
        return new RestResponse(SystemCode.ParameterValidError.getCode(),errorMsg);
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public RestResponse handler(BindException e){
        String errorMsg = e.getBindingResult().getAllErrors().stream().map(file -> {
            FieldError fieldError = (FieldError) file;
            return ErrorUtil.parameterErrorFormat(fieldError.getField(), fieldError.getDefaultMessage());
        }).collect(Collectors.joining());
        return new RestResponse(SystemCode.ParameterValidError.getCode(),errorMsg);
    }

}
